<template>
  <el-card>
    <template #header>
      <h3 v-text="t('controller')"></h3>
    </template>
    
    <!-- 数据路径 -->
    <el-row :gutter="8" style="align-items: center;">
      <el-col :span="4">
        <span v-text="t('data_path')"></span>
      </el-col>
      <el-col :span="12">
        <div>{{ controllerStore.dataPath }}</div>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="primary" 
          @click="showSessionList"
          :disabled="!controllerStore.canAccessSessionList"
          style="width: 100%;"
        >
          {{ t('sessions') }}
        </el-button>
      </el-col>
      <el-col :span="4">
        <el-button 
          type="primary" 
          @click="selectDataPath"
          :disabled="!controllerStore.canSelectDataPath"
          style="width: 100%;"
        >
          {{ t('select') }}
        </el-button>
      </el-col>
    </el-row>

    <!-- 应用模式 -->
    <el-row :gutter="8">
      <el-col :span="18">
        <el-radio-group 
          class="full-width-radio-group"
          v-model="appMode" 
          :disabled="!controllerStore.isIdle"
          @change="handleAppModeChange"
        >
          <el-radio-button label="online">{{ t('online') }}</el-radio-button>
          <el-radio-button label="remote">{{ t('remote') }}</el-radio-button>
          <el-radio-button label="offline">{{ t('offline') }}</el-radio-button>
          <el-radio-button label="replay">{{ t('replay') }}</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="6">
        <el-button 
          type="primary" 
          @click="showGenerationSetting"
          :disabled="!controllerStore.canAccessGenerationSetting"
          style="width: 100%;"
        >
          {{ t('generation') }}
        </el-button>
      </el-col>
    </el-row>

    <!-- 控制按钮 -->
    <el-row :gutter="8">
      <el-col :span="8">
        <el-button 
          :type="controllerStore.previewButtonType"
          @click="controllerStore.startPreview"
          :disabled="!controllerStore.canPreview"
          style="width: 100%;"
        >
          {{ t('preview') }}
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button 
          :type="controllerStore.recordButtonType"
          @click="controllerStore.startRecord"
          :disabled="!controllerStore.canRecord"
          style="width: 100%;"
        >
          {{ t('record') }}
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button 
          :type="controllerStore.stopButtonType"
          @click="controllerStore.stop"
          :disabled="!controllerStore.isRunning"
          style="width: 100%;"
        >
          {{ t('stop') }}
        </el-button>
      </el-col>
    </el-row>

    <!-- 缓冲区信息 -->
    <el-row :gutter="8">
      <el-col :span="24">
        <el-row :gutter="8" style="align-items: center; margin-bottom: 0px;">
          <el-col :span="8">
            <div style="text-align: center;">
              <div>{{ t('buffer_begin') }}</div>
              <div>{{ formatTime(controllerStore.bufferBegin) }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: center;">
              <div>{{ t('interest') }}</div>
              <div>{{ formatTime(controllerStore.interestTime) }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div style="text-align: center;">
              <div>{{ t('buffer_end') }}</div>
              <div>{{ formatTime(controllerStore.bufferEnd) }}</div>
            </div>
          </el-col>
        </el-row>
        <el-slider
          v-model="interestRatio"
          :min="0"
          :max="1"
          :step="0.001"
          :show-tooltip="false"
          :disabled="!controllerStore.isRunning"
          @input="handleInterestChange"
        />
      </el-col>
    </el-row>

    <!-- 回放速度 -->
    <el-row :gutter="8" v-if="controllerStore.showReplaySpeed">
      <el-col :span="24">
        <el-row :gutter="8" justify="center" style="align-items: center; margin-bottom: 0px;">
          <el-col :span="6" style="text-align: right;">
            <span v-text="t('replay_speed')"></span>
          </el-col>
          <el-col :span="12">
            <span>{{ controllerStore.formatReplaySpeed }}</span>
          </el-col>
        </el-row>
        <el-slider
          v-model="replaySpeedRatio"
          :min="0"
          :max="1"
          :step="0.001"
          :show-tooltip="false"
          @input="handleReplaySpeedChange"
        />
      </el-col>
    </el-row>

    <!-- 手动触发按钮 -->
    <el-row :gutter="8">
      <el-col :span="24">
        <div style="text-align: center; margin-bottom: 0px;">
          <span v-text="t('manual_trigger')"></span>
        </div>
        <el-row :gutter="4" style="margin-bottom: 4px;">
          <el-col :span="3" v-for="i in 8" :key="i">
            <el-button 
              type="primary" 
              size="small"
              @click="controllerStore.sendManualTrigger(i-1)"
              :disabled="!controllerStore.isRunning"
              style="width: 100%;"
            >
              {{ String.fromCharCode(64 + i) }}
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="4">
          <el-col :span="3" v-for="i in 8" :key="i+8">
            <el-button 
              type="primary" 
              size="small"
              @click="controllerStore.sendManualTrigger(i+7)"
              :disabled="!controllerStore.isRunning"
              style="width: 100%;"
            >
              {{ String.fromCharCode(72 + i) }}
            </el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useControllerStore } from '@/stores/controller'
import { useLanguageStore } from '@/stores/language'
import { useSessionListStore } from '@/stores/sessionList'
import { useGenerationSettingStore } from '@/stores/generationSetting'

const controllerStore = useControllerStore()
const languageStore = useLanguageStore()
const sessionListStore = useSessionListStore()
const generationSettingStore = useGenerationSettingStore()

// 状态
const interestRatio = ref(0)
const replaySpeedRatio = ref(0)
const appMode = ref('online')

// 监听缓冲区变化，更新interestRatio
watch(
  () => [controllerStore.bufferBegin, controllerStore.bufferEnd, controllerStore.interestTime],
  ([begin, end, interest]) => {
    if (end > begin) {
      if (interest === Infinity) {
        interestRatio.value = 1
      } else {
        interestRatio.value = (interest - begin) / (end - begin)
      }
    } else {
      interestRatio.value = 0
    }
  },
  { immediate: true }
)

// 监听回放速度变化，更新replaySpeedRatio
watch(
  () => controllerStore.targetReplaySpeed,
  (speed) => {
    speed = Math.max(0, Math.min(16, speed))
    if (speed <= 2.0) {
      replaySpeedRatio.value = speed * 0.2
    } else {
      replaySpeedRatio.value = Math.log2(speed) * 0.2 + 0.2
    }
    replaySpeedRatio.value = Math.max(0, Math.min(1, replaySpeedRatio.value))
  },
  { immediate: true }
)

// 监听应用模式变化，更新appMode
watch(
  () => [
    controllerStore.isOnlineMode,
    controllerStore.isRemoteMode,
    controllerStore.isOfflineMode,
    controllerStore.isReplayMode
  ],
  ([isOnline, isRemote, isOffline, isReplay]) => {
    if (isOnline) appMode.value = 'online'
    else if (isRemote) appMode.value = 'remote'
    else if (isOffline) appMode.value = 'offline'
    else if (isReplay) appMode.value = 'replay'
  },
  { immediate: true }
)

// 方法
function formatTime(time) {
  return time.toLocaleString('en', { minimumFractionDigits: 3, useGrouping: false })
}

function handleInterestChange() {
  const ratio = interestRatio.value
  if (ratio >= 0.999) {  // 使用0.999作为阈值，因为浮点数比较可能会有精度问题
    controllerStore.setInterestTime(Infinity)
  } else {
    const time = controllerStore.bufferBegin + 
      (controllerStore.bufferEnd - controllerStore.bufferBegin) * ratio
    controllerStore.setInterestTime(time)
  }
}

function handleReplaySpeedChange() {
  const ratio = replaySpeedRatio.value
  let speed = 0
  if (ratio <= 0.4) {
    speed = ratio * 5
  } else {
    speed = Math.pow(2, (ratio - 0.2) * 5)
  }
  speed = Math.max(0, Math.min(16, speed))
  controllerStore.setTargetReplaySpeed(speed)
}

function handleAppModeChange(mode) {
  switch (mode) {
    case 'online':
      controllerStore.switchToOnlineMode()
      break
    case 'remote':
      controllerStore.switchToRemoteMode()
      break
    case 'offline':
      controllerStore.switchToOfflineMode()
      break
    case 'replay':
      controllerStore.switchToReplayMode()
      break
  }
}


// 翻译函数
const t = (key) => {
  const translations = {
    'controller': {
      'en': 'Controller',
      'zh': '控制'
    },
    'data_path': {
      'en': 'Data path:',
      'zh': '数据路径:'
    },
    'sessions': {
      'en': 'Sessions',
      'zh': '列表'
    },
    'select': {
      'en': 'Select',
      'zh': '选择'
    },
    'online': {
      'en': 'Online',
      'zh': '在线'
    },
    'remote': {
      'en': 'Remote',
      'zh': '远程'
    },
    'offline': {
      'en': 'Offline',
      'zh': '离线'
    },
    'replay': {
      'en': 'Replay',
      'zh': '回放'
    },
    'generation': {
      'en': 'Generation',
      'zh': 'Generation'
    },
    'preview': {
      'en': 'Preview',
      'zh': '预览'
    },
    'record': {
      'en': 'Record',
      'zh': '记录'
    },
    'stop': {
      'en': 'Stop',
      'zh': '停止'
    },
    'buffer_begin': {
      'en': 'Buffer begin',
      'zh': '缓存起点'
    },
    'interest': {
      'en': 'Interest',
      'zh': '兴趣点'
    },
    'buffer_end': {
      'en': 'Buffer end',
      'zh': '缓存终点'
    },
    'replay_speed': {
      'en': 'Replay speed',
      'zh': '回放速度'
    },
    'manual_trigger': {
      'en': 'Manual trigger',
      'zh': '手动触发'
    }
  }
  return translations[key]?.[languageStore.isChinese ? 'zh' : 'en'] || key
}

// 实现这些方法
async function showSessionList() {
  await sessionListStore.show()
}

async function selectDataPath() {
  await controllerStore.runDataPathConfigWorkflow()
}

async function showGenerationSetting() {
  await generationSettingStore.show()
}

// 初始化
onMounted(async () => {
  await controllerStore.updateControllerPanelAvailability()
})
</script> 